package com.sys;

import io.rong.app.DemoContext;
import io.rong.app.SOSOLocationActivity;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongIM.ConversationBehaviorListener;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation.ConversationType;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.moon.ImageShowActivity;
import com.moon.MainTabActivity;
import com.moon.MineActivity;
import com.moon.NotifyMessageHandler;
import com.moon.PersonInfoActivity;
import cn.yueliangbaba.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.MemoryCacheAware;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.message.PushAgent;
import com.util.Constant;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.widget.CircleImageView;

public class DemoApp extends Application {
	static private Context mContext;
	private List<Activity> activities = new ArrayList<Activity>();
	public List<Integer> mClassesSelected = new ArrayList<Integer>();
	public List<Bitmap> mBitmapArray = new ArrayList<Bitmap>();
	
	public JSONObject mMembers = new JSONObject();
	public JSONObject mClasses = new JSONObject();
	public JSONObject mIdentfy = new JSONObject();
	public JSONArray mBabyList = null;
	public int mSelectedBaby = 0;
	
	public int mTab = -1;
	
	@SuppressLint("NewApi")
	@Override
	public void onCreate() {
		super.onCreate();

		if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext())) ||
                "io.rong.push".equals(getCurProcessName(getApplicationContext()))) {
            RongIM.init(this);
            DemoContext.init(this);
        }
		
		mContext = getApplicationContext();

		if (Constants.DEBUG_MODE
				&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectDiskReads().detectDiskWrites().detectNetwork() 
					.penaltyLog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
					.detectLeakedSqlLiteObjects().penaltyLog().build());
		}

		if (!Constants.DEBUG_MODE) {
			MyUncaughtExceptionHandler exceptionHandler = new MyUncaughtExceptionHandler();
			Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
		}

		initImageLoader(getApplicationContext());
		
		String token = PreferencesUtils.getString(this, "im_token");
		if(token != null && token.length() > 0)
		{
			connect(token);
		}
		
		String member = PreferencesUtils.getString(mContext, "all_members");
		if(member != null && member.length() > 0)
		{
			mMembers = JSON.parseObject(member);
		}
		
		setClasses();
		setIdentify();
		initFinal();
		initUmeng();
	}
	
	public void cleanBitmap()
	{
		int count = mBitmapArray.size();
		for(int i = count - 1; i>= 0;i--)
		{
			Bitmap bitmap = mBitmapArray.get(i);
			mBitmapArray.remove(i);
			bitmap.recycle();
			bitmap = null;
			System.gc();
		}
	}
	
	void initUmeng(){
		NotifyMessageHandler messageHandler = new NotifyMessageHandler(){

		};
		
		PushAgent mPushAgent = PushAgent.getInstance(this);
		mPushAgent.enable();
		mPushAgent.setMessageHandler(messageHandler);
	}
	
	void initFinal()
	{
		//配置主题
//		//ThemeConfig.CYAN
//		ThemeConfig theme = new ThemeConfig.Builder()
//				.setTitleBarBgColor(Color.rgb(0xFF, 0x57, 0x22))
//		        .build();
//		//配置功能
//		FunctionConfig functionConfig = new FunctionConfig.Builder()
//		        .setEnableCamera(true)
//		        .setEnableEdit(true)
//		        .setEnableCrop(true)
//		        .setEnableRotate(true)
//		        .setCropSquare(true)
//		        .setEnablePreview(true)
//		        .build();
//
//		//配置imageloader
//		UILImageLoader imageloader = new UILImageLoader();      
//		//设置核心配置信息 
//		CoreConfig coreConfig = new CoreConfig.Builder(mContext, imageloader, theme)
//		        .setFunctionConfig(functionConfig)
//		        .build();
//		GalleryFinal.init(coreConfig);
	}
	
	public void setIdentify()
	{
		String identify = PreferencesUtils.getString(mContext, "identitylabel");
		if(identify != null && identify.length() > 0)
		{
			JSONArray  array = JSON.parseArray(identify);
			int count = array.size();
			for(int i = 0; i < count; i++)
			{
				JSONObject item = array.getJSONObject(i);
				mIdentfy.put(item.getString("id"),item.getString("name"));
			}
		}
	}
	
	public void setClasses()
	{
		String classes = PreferencesUtils.getString(mContext, "classes");
		if(classes != null && classes.length() > 0)
		{
			JSONArray array = JSON.parseArray(classes);
			int count = array.size();
			for(int i = 0; i < count; i++)
			{
				JSONObject item = array.getJSONObject(i);
				String className = item.getString("class_name");
				if(item.getString("class_alias") != null && item.getString("class_alias").length() > 0) className = item.getString("class_alias");
				
				mClasses.put(item.getString("id"), className);
			}
		}
	}
	
	/**
	 * 建立与融云服务器的连接
	 *
	 * @param token
	 */
	public void connect(String token) {
		RongIM.setConversationBehaviorListener(new ConversationBehaviorListener(){
			@Override
			public boolean onMessageClick(Context arg0, View arg1, Message message) {
				if (message.getContent() instanceof ImageMessage) {
					if (message.getContent() != null) {
						Intent intent = new Intent(mContext, ImageShowActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						Uri uri = ((ImageMessage) message.getContent()).getRemoteUri();
						if (uri == null) {
							return false;
						}
						intent.putExtra("imgs", uri.toString());
						intent.putExtra("index", 0);
						mContext.startActivity(intent);
					}
					
					return true;
				}
				else if(message.getContent() instanceof LocationMessage)
				{
					Intent intent = new Intent(mContext, SOSOLocationActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra("location", message.getContent());
					mContext.startActivity(intent);
					return true;
				}

				return false;
			}

			@Override
			public boolean onMessageLinkClick(Context arg0, String arg1) {
				return false;
			}

			@Override
			public boolean onMessageLongClick(Context arg0, View arg1,
					Message arg2) {
				return false;
			}

			@Override
			public boolean onUserPortraitClick(Context arg0,
					ConversationType arg1, UserInfo arg2) {
				Intent intent = new Intent(arg0,PersonInfoActivity.class);
				intent.putExtra("name", arg2.getName());
				intent.putExtra("userId", arg2.getUserId());
				arg0.startActivity(intent);
				
				return true;
			}

			@Override
			public boolean onUserPortraitLongClick(Context arg0,
					ConversationType arg1, UserInfo arg2) {
				return false;
			}
		});
		
	    if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {

	        /**
	         * IMKit SDK调用第二步,建立与服务器的连接
	         */
	        RongIM.connect(token, new RongIMClient.ConnectCallback() {

	            /**
	             * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
	             */
	            @Override
	            public void onTokenIncorrect() {
	            }

	            /**
	             * 连接融云成功
	             * @param userid 当前 token
	             */
	            @Override
	            public void onSuccess(String userid) {
	            	RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
						@Override
						public UserInfo getUserInfo(String userId) {
							if(mMembers == null)
							{
								return new UserInfo(userId,"",Uri.parse("http://odv1e0gp0.bkt.clouddn.com/ic_teacher.png"));
							}

							JSONObject item = mMembers.getJSONObject(userId);
							if(item == null)
							{
								return new UserInfo(userId,"",Uri.parse("http://odv1e0gp0.bkt.clouddn.com/ic_teacher.png"));
							}
							
							
							String path = null;
							try
							{
								path = item.getString("avatar");
							}catch(Exception e){}
							if(path == null || path.length() == 0)
							{
								if(item.getInteger("is_teacher") == 1) path = "http://odv1e0gp0.bkt.clouddn.com/ic_teacher.png";
								else path = "http://odv1e0gp0.bkt.clouddn.com/ic_family.png";
							}
							else path = "http://120.27.129.233/ylbb/" + path;
							
							String name = item.getString("username");
							if(item.getString("alias") != null  && item.getString("alias").length() != 0) name = item.getString("alias");
							if(userId.equals(PreferencesUtils.getString(mContext, "userId")))
							{
								name = "我";
							}
							
							Log.e("------", name + ";" + userId + ";" + path);
							
							return new UserInfo(userId,name,Uri.parse(path));//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
						}
					}, true);
	            	/*
	            	try
	            	{
		            	JSONObject member = JSON.parseObject(PreferencesUtils.getString(mContext, "member"));
		            	String path = member.getString("avatar_path");
						if(path == null || path.length() == 0) path = "static/upload/avatar/default.jpg";
						
		            	RongIM.getInstance().setCurrentUserInfo(new UserInfo(member.getString("id"),
		            			member.getString("username"),Uri.parse("http://120.27.129.233/ylbb/" + path)));   
		            	RongIM.getInstance().setMessageAttachedUserInfo(true);
	            	}catch(Exception e){}*/
	            }

	            /**
	             * 连接融云失败
	             * @param errorCode 错误码，可到官网 查看错误码对应的注释
	             */
	            @Override
	            public void onError(RongIMClient.ErrorCode errorCode) {
	            }
	        });
	    }
	}
	
	public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }
	
	public void sendGetBabyRequest(Context context) {
		MgqDataHandler loginHandler = new MgqDataHandler(context, true, false) {
			@Override
			public void onSuccess(String response) {
				((DemoApp)getApplicationContext()).mBabyList = JSON.parseArray(response);
				if(((DemoApp)getApplicationContext()).mBabyList != null)
				{
					int count = ((DemoApp)getApplicationContext()).mBabyList.size();
					for(int i = 0; i < count; i++)
					{
						JSONObject item = ((DemoApp)getApplicationContext()).mBabyList.getJSONObject(i);
						if(item.getString("isCurr").equals("true")) ((DemoApp)getApplicationContext()).mSelectedBaby = i;
					}
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("handType", "get");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/babyInfoHandler.ashx", JSON.toJSONString(params), loginHandler);
	}

	public JSONObject getSeletedBaby()
	{
		if(mBabyList != null) return mBabyList.getJSONObject(mSelectedBaby);
		return null;
	}

	public void addActivity(Activity activity) {
		activities.add(activity);
	}

	public void removeActivity(Activity activity) {
		activities.remove(activity);
	}

	public List<Activity> getActivityList() {
		return activities;
	}

	@Override
	public void onTerminate() {

		super.onTerminate();
		exit();
	}

	public void exit() {
		for (Activity activity : activities) {
			activity.finish();
		}
		System.exit(0);
	}

	public int getActivitySize() {
		return activities.size();
	}

	public static boolean isIntentAvailable(Context context, Intent intent) {
		final PackageManager packageManager = context.getPackageManager();
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.GET_ACTIVITIES);
		return list.size() > 0;
	}

	public static void initImageLoader(Context context) {
		int memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 2);

		MemoryCacheAware<String, Bitmap> memoryCache;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			memoryCache = new LruMemoryCache(memoryCacheSize);
		} else {
			memoryCache = new LRULimitedMemoryCache(memoryCacheSize);
		}

		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.memoryCache(memoryCache).denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.FIFO).build();
		// .tasksProcessingOrder(QueueProcessingType.LIFO).build();

		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		// com.nostra13.universalimageloader.utils.L.setLogEnable(false);
	}
	
	static public Context getContext()
	{
		return mContext;
	}
	
	public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {

		private final String TAG = "MyUncaughtExceptionHandler";
		private UncaughtExceptionHandler exceptionHandler;

		private MyUncaughtExceptionHandler() {
			exceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
		}

		@Override
		public void uncaughtException(Thread thread, Throwable ex) {
			Log.d(TAG, "get UncaughtException!!!");
			ex.printStackTrace();

			handle.sendEmptyMessage(0);
		}
	}
	
	Handler handle = new Handler(){
		public void handleMessage(android.os.Message msg)
		{
			super.handleMessage(msg);
			if(MainTabActivity.mMainTabActivity != null) MainTabActivity.mMainTabActivity.finish();
			
	        final Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(
	        		mContext.getPackageName());  
	        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
	        mContext.startActivity(intent);  
		}
	};
}
